package com.example.everying.controller.system;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.annotation.WebLog;
import com.example.everying.context.UserContext;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.model.dto.chat.LocationDto;
import com.example.everying.model.dto.content.ArtInfoDto;
import com.example.everying.model.dto.system.SysNotificationDto;
import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.model.vo.SysNotificationVo;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.chat.WebSocketBroadcastService;
import com.example.everying.service.system.SysNotificationService;
import com.example.everying.utils.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "系统通知")
@RequestMapping("/system/notice")
@RequiredArgsConstructor
public class SysNoticeController {
    @Autowired
    private WebSocketBroadcastService webSocketBroadcastService;
    @Autowired
    private SysNotificationService sysNotificationService;

    @ApiOperation(value = "系统通知列表")
    @PostMapping("/comment/page")
    @WebLog(description = "系统通知列表")
    public Result<?> recharge(@ApiParam(name = "SysNotificationDto", value = "系统通知请求参数", required = true)
                              @RequestBody SysNotificationDto dto) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            return Result.fail("用户未登录");
        }
        Page<SysNotification> pageParam = new Page<>(dto.getPage(), dto.getLimit());
        dto.setRecipientId(userInfoVo.getId());
        IPage<SysNotification> page = sysNotificationService.selectPage(pageParam, dto);
        // 转换为VO对象
        Page<SysNotificationVo> pageVo = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<SysNotificationVo> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            voList = page.getRecords().stream().map(notification -> {
                SysNotificationVo vo = new SysNotificationVo();
                vo.setSysNotification(notification);
                if (notification.getArtInfo() != null) {
                    vo.setArtInfoDto(JSON.parseObject(notification.getArtInfo(), ArtInfoDto.class));
                }
                return vo;
            }).collect(Collectors.toList());
        }

        pageVo.setRecords(voList);
        // 更新用户通知状态 改成已读
        UpdateWrapper<SysNotification> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("recipient_id", userInfoVo.getId());
        updateWrapper.set("msg_status", "1");
        sysNotificationService.update(updateWrapper);
        return Result.ok(pageVo);
    }

    // ========== 新增通知 ==========
    @ApiOperation("新增系统通知")
    @PostMapping("/add")
    @WebLog(description = "新增系统通知")
    public Result<?> add(@ApiParam(name = "SysNotification", value = "通知内容", required = true)
                         @Valid @RequestBody SysNotification notification) {
        boolean success = sysNotificationService.saveNotification(notification);
        return success ? Result.ok() : Result.fail("新增失败");
    }

    // ========== 修改通知 ==========
    @ApiOperation("修改系统通知")
    @PostMapping("/update")
    @WebLog(description = "修改系统通知")
    public Result<?> update(@ApiParam(name = "SysNotification", value = "通知内容", required = true)
                            @Valid @RequestBody SysNotification notification) {
        boolean success = sysNotificationService.updateNotificationById(notification);
        return success ? Result.ok() : Result.fail("修改失败");
    }

    // ========== 删除通知 ==========
    @ApiOperation("删除系统通知")
    @PostMapping("/delete/{id}")
    @WebLog(description = "删除系统通知")
    public Result<?> delete(@ApiParam(name = "id", value = "通知ID", required = true)
                            @PathVariable Long id) {
        boolean success = sysNotificationService.deleteNotificationById(id);
        return success ? Result.ok() : Result.fail("删除失败");
    }
    @ApiOperation("删除已读的系统通知")
    @PostMapping("/delete/batch")
    @WebLog(description = "删除已读的系统通知")
    public Result<?> deleteBatch() {
        boolean success = sysNotificationService.deleteNotificationBatch();
        return success ? Result.ok() : Result.fail("删除失败");
    }

    @ApiOperation("广播系统通知")
    @PostMapping("/broadcast")
    @WebLog(description = "广播系统通知")
    public Result<?> broadcast(@ApiParam(name = "SysNotification", value = "通知内容", required = true)
                               @Valid @RequestBody SysNotification notification) {
        webSocketBroadcastService.broadcastSystemNotification(String.valueOf(notification.getId()));
        return Result.ok();
    }
}
